<?php

namespace Home\Controller;
use Home\Controller\BaseController;

class OssController extends BaseController{
    private $ossClient;
    public function __construct(){
        parent::__construct();
        require_once(I('server.DOCUMENT_ROOT') . '/aliOSS/' . 'autoload.php');
        $accessKeyId = "QTOlfzI9L0f4v7iR"; ;
        $accessKeySecret = "I13fvf4xeFRoBMPCfFgoUT18oA0OJy";
        $endpoint = "http://oss-cn-hangzhou-internal.aliyuncs.com";
        try {
            $this->ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
        } catch (OssException $e) {
            print $e->getMessage();
        }
    }

    public function  test()
    {
        $info['Action'] = 'DescribeLiveStreamRecordIndexFiles';
        $info['DomainName'] = 'jwlive.appwuhan.com';
        $info['AppName'] = 'jw';
        $info['StreamName'] = '20160920112925_20_57e0ad15559b3_20';
        $info['StartTime'] = '2016-09-01T17:36:00Z';
        $info['EndTime'] = '2016-09-30T16:36:00Z';

        $requestid = callAliyunApi($info);
        $requestid = json_decode($requestid, true);

        dump($requestid['RecordIndexInfoList']['RecordIndexInfo']);
    }

    public function ajaxMediaList($id='',$sTime=0,$eTime=''){
        if($id){
            date_default_timezone_set("Etc/GMT");
            if(!$eTime){
                $eTime=date(DATE_ISO8601).'Z';
            }else{
                $eTime=date(DATE_ISO8601,strtotime($eTime.' 23:59:59')).'Z';
            }

            $eTime=str_replace("+0000","Z",$eTime);
            if(!$sTime){
                $sTime=strtotime(date('Y-m-d 00:00:00',time()-3600*24*2));
                $sTime=date(DATE_ISO8601,$sTime).'Z';
            }else{
                $sTime=date(DATE_ISO8601,strtotime($sTime.' 00:00:00')).'Z';
            }
            $sTime=str_replace("+0000","",$sTime);

            $live=M('Live')->field('id,group_id,realnamepy,userchannel,apply_time,user_id,return_live,is_device')
                ->alias('l')
                ->join('__USER_INFO__ ui on l.user_id=ui.uid')
                ->find($id);
            if($live['userchannel']==55 or $live['is_device']==1){
                $stream=$live['realnamepy'];
            }else{
                $stream=$live['group_id'].'_'.$live['user_id'];
            }
            //拉取对应stream的全部M3U8
            $info['Action'] = 'DescribeLiveStreamRecordIndexFiles';
            $info['DomainName'] = 'jwlive.appwuhan.com';
            if($live['userchannel']==57){
                $info['AppName'] = 'jwdev';
            } else {
                $info['AppName'] = 'jw';
            }
            $info['StreamName'] = $stream;
            $info['StartTime'] = $sTime;
            $info['EndTime'] = $eTime;
            //date_default_timezone_set("Etc/GMT+8");
            $requestid = callAliyunApi($info);
            $requestid = json_decode($requestid, true);
            //dump($requestid['RecordIndexInfoList']['RecordIndexInfo']);
            echo '<div style="margin-bottom:15px">回看地址： <input type="text" class="form-control" id="re_live" name="return_live" value="'.$live['return_live'].'" style="width:75%;" /> <button type="button" class="btn btn-ms btn-warning" onclick="editReturn('.$live['id'].',this)">确定修改</button></div>';
            if(count($requestid['RecordIndexInfoList']['RecordIndexInfo'])==0){
                echo ('<div class="alert alert-info" role="alert">没有视频文件</div>') ;
            }else{
                $showlen=26;//列表显示条数
                $infoArr=$requestid['RecordIndexInfoList']['RecordIndexInfo'];
                foreach ($infoArr as $key => $row) {
                    $StartTime[$key]  = $row['StartTime'];
                    $EndTime[$key]  = $row['EndTime'];
                    $RecordUrl[$key]  = $row['RecordUrl'];
                    $OssObject[$key]  = $row['OssObject'];
                }
                array_multisort($StartTime, SORT_DESC, $EndTime, SORT_ASC, $RecordUrl, SORT_ASC,$OssObject, SORT_ASC,$infoArr);

                if(count($infoArr)>$showlen){
                    $infoArr=array_splice($infoArr,0, $showlen);
                }
                $str = '<div class="alert alert-danger" role="alert" style="font-size:14px;padding:5px">注意：请<strong>先点击转码</strong>，完成后<strong>再右键点击下载按钮，选择“另存为”</strong>，进行下载</div>';

                foreach($infoArr as $k=>$v){
                    $str.='<li>'.($k+1) .'、<span class="vtime" data-duration="'.$v['Duration'].'">'.date("Y-m-d H:i:s",strtotime(str_replace("Z",'-08:00',$v['StartTime']))).' — '.date("H:i:s",strtotime(str_replace("Z",'-08:00',$v['EndTime']))).'</span>';

                    if($live['return_live'] == $v['RecordUrl']) {
                        $str .= ' <span class="alert  alert-success" style="font-size: 12px;padding:2px">回看中...</span> ';
                    } else {
                        $str .= ' <a class="btn btn-xs btn-info returnLive" data-id="' . $live['id'] . '" data-url="' . $v['RecordUrl'] . '" href="javascript:;">回看</a> ';
                    }
                    $str.='<span id="s_'.$k.'">';
                    $res=M('LiveStream')->field('stream_id,attachment_url')->where(array('stream_name'=>$v['OssObject']))->find();
/*                    if($res){
                        switch($res['attachment_url']){
                            case "-1":
                                $str.='<button type="button" class="btn btn-xs btn-info getURL" data-stream="'.$v['OssObject'].'">转码</button></span>';
                                break;
                            case "0":
                                $str.='<img src="/Public/live/img/mtsloading.gif"  data-streamId="'.$res['stream_id'].'" />  转码中...';
                                break;
                            default:
                                $str.='<a class="btn btn-xs btn-danger downloadMts" target="downloadif"  href="http://download.appwuhan.net/Live/download.html?id='.$res['stream_id'].'">下载</a>';
                        }
                    }else{
                        $str.='<button type="button" class="btn btn-xs btn-info getURL"  data-stream="'.$v['OssObject'].'">转码</button></span>';
                    }*/
                    $str.=' <button type="button" class="btn btn-xs btn-info previewStream"  data-oss="'.$v['OssObject'].'" data-stream="'.$info['AppName'].'/'.$info['StreamName'].'">预览</button></span>';

                    $str.='</span></li>';
                }
                if(count($requestid['RecordIndexInfoList']['RecordIndexInfo'])>$showlen){
                    $str.='<li class="bg-info">还有更多视频请输入时间查询</li>';
                }
                echo $str;
            }
        }else{
            echo ('<div class="alert alert-danger" role="alert">参数错误！</div>');
        }
    }

    public function transMTS($file,$liveid){
        $res=gethttpcurl('http://resource.local.appwuhan:'.C('HOST_PORT').U('Live/Oss/transMTS').'?stream='.$file.'&liveid='.$liveid);
        $this->ajaxReturn(json_decode($res,true));
    }

    public function ajaxGetProgress($stream_id=''){
        if($stream_id){
            $res=M('LiveStream')->field('percent')->find($stream_id);
            if($res){
                $message['status'] = 1;
                $message['msg'] = $res['percent'];
            }else{
                $message['status'] = 0;
                $message['msg'] = '服务器错误！';
            }
        }else{
            $message['status'] = -1;
            $message['msg'] = '参数错误';
        }
        $this->ajaxReturn($message);
    }

    /**
     * 获取回看M3U8地址
     * @param  string  $id    [description]
     * @param  integer $sTime [description]
     * @param  string  $eTime [description]
     * @return [type]         [description]
     */
    public function ajaxM3u8List($id='',$sTime=0,$eTime=''){
        if($id){
            date_default_timezone_set("Etc/GMT");
            if(!$eTime){
                $eTime=date(DATE_ISO8601).'Z';
            }else{
                $eTime=date(DATE_ISO8601,strtotime($eTime.' 23:59:59')).'Z';
            }

            $eTime=str_replace("+0000","Z",$eTime);
            if(!$sTime){
               $sTime=strtotime(date("Y-m-d 00:00:00",time()-3600*24*2)); 

                $sTime=date(DATE_ISO8601,$sTime).'Z';
            }else{
                $sTime=date(DATE_ISO8601,strtotime($sTime.' 00:00:00')).'Z';
            }
            $sTime=str_replace("+0000","",$sTime);

            $live=M('Live')->field('id,group_id,realnamepy,userchannel,apply_time,user_id,return_live')
            ->alias('l')
            ->join('__USER_INFO__ ui on l.user_id=ui.uid')
            ->find($id);

            // $live=M('Live')->field('group_id,apply_time,user_id')->find($id);
            $stream=$live['group_id'].'_'.$live['user_id'];
            //拉取对应stream的全部M3U8
            $info['Action'] = 'DescribeLiveStreamRecordIndexFiles';
            $info['DomainName'] = 'jwlive.appwuhan.com';
            if($live['userchannel']==57){
                $info['AppName'] = 'jwdev';
            } else {
                $info['AppName'] = 'jw';
            }
            $info['StreamName'] = $stream;
            $info['StartTime'] = $sTime;
            $info['EndTime'] = $eTime;
            //date_default_timezone_set("Etc/GMT+8");
            $requestid = callAliyunApi($info);
            $requestid = json_decode($requestid, true);

            return $requestid['RecordIndexInfoList']['RecordIndexInfo'];

            // $this->ajaxReturn($requestid['RecordIndexInfoList']['RecordIndexInfo'][count($requestid['RecordIndexInfoList']['RecordIndexInfo']) - 1]);
        }
    }

    public function ajaxSetReturnLive() {
        $id = I('post.id');
        $url = I('post.url');
        if($id) {
            if($url) {
                $res = M('Live')->where(array('id' => $id))->save(array(
                    'return_live' => $url,
                ));

                if($res !== false) {
                    $this->ajaxReturn(1);
                } else {
                    $this->ajaxReturn(0);
                }

            } else {
                $this->ajaxReturn(0);
            }

        } else {
            $this->ajaxReturn(0);
        }
    }

    public function ajaxMakeM3U8(){
        $sTime=I('get.sTime');
        $eTime=I('get.eTime');
        $stream=I('get.stream');

        if($sTime && $eTime && $stream){
            date_default_timezone_set("Etc/GMT");
            $eTime=date(DATE_ISO8601,floor($eTime)).'Z';
            $eTime=str_replace("+0000","",$eTime);
            $sTime=date(DATE_ISO8601,floor($sTime)).'Z';
            $sTime=str_replace("+0000","",$sTime);

            $tmp=explode("/",$stream);
            $StreamName=$tmp[1];

            $info['Action'] = 'CreateLiveStreamRecordIndexFiles';
            $info['DomainName'] = 'jwlive.appwuhan.com';
            $info['AppName'] = $tmp[0];
            $info['StreamName'] = $StreamName;
            $info['StartTime'] = $sTime;
            $info['EndTime'] = $eTime; 
            $info['OssEndpoint'] = "oss-cn-hangzhou.aliyuncs.com";
            $info['OssBucket'] = 'whtv-out';
            $info['OssObject'] = "record/{$tmp[0]}/".$StreamName."_new_".time().".m3u8";

            $requestid = callAliyunApi($info);
            $requestid = json_decode($requestid, true);
            if(isset($requestid['RecordInfo']) && is_array($requestid['RecordInfo'])){
                $res['code']=0;
                $res['info']=$requestid['RecordInfo'];
            }else{
                $res['code']=1;
                $res['info']=$requestid;
                $res['msg']="裁剪失败，请重试！";
            }
        }else{
            $res['code']=1;
            $res['msg']="参数错误！";
        }
        $this->ajaxReturn($res);
    }
}